<template>
  <!--  支付页面 -->
  <view class="payment-container">
    <!-- 顶部导航 -->
    <view class="nav-bar" @click="goToAddressPage">
      <view class="nav-title">
        <img class="address-icon" src="../static/imgs/dizhi.png" alt="">
        <div class="title">{{ Address.contactAddress }}</div>
        <img src="../static/imgs/jiantou.png" alt="">
      </view>
      <div class="nav-info">
        <div>{{ Address.contactName }}</div>
        <div>{{ Address.contactPhone }}</div>
      </div>
    </view>

    <!-- 购物车商品列表 -->
    <div class=wrapper-box>
      <div class="wrapper-box-content">
        <div class="item-content">
          <template v-for="(item, index) in cartItems" :key="index">
            <div class="item-content-item">
              <img :src="item.thumbnail ? item.thumbnail : '../static/imgs/caipinmoren.png'" alt="">
              <div class="item-content-item-title">
                <div class="one">{{ item.goodsName }}</div>
                <div class="two">
                  <template v-for="(spec, specIndex) in item.specDetails" :key="specIndex">
                    <span>{{ spec.optionName }}: {{ spec.specsName }}
                      <span v-if="Number(spec.specsPrice) > 0" style="color: red;"> +￥{{ spec.specsPrice }}</span>
                      <span v-if="specIndex < item.specDetails.length - 1">; </span>
                    </span>
                  </template>
                </div>
                <div class="four">
                  <div class="four-left">
                    <span>￥</span>
                    <span>{{
                      (
                        parseFloat(item.listGoodsSkus?.[0]?.priceStr || item.listGoodsSkus?.[0]?.marketPrice || 0) +
                        (item.specDetails?.reduce((sum, spec) => sum + (parseFloat(spec.specsPrice) || 0), 0) || 0)
                      ).toFixed(2)
                    }}</span>
                    <span v-if="Number(item.listGoodsSkus?.[0]?.packPriceStr) > 0"
                      style="font-size: 20rpx; margin-left: 8rpx;">+打包费¥{{
                        item.listGoodsSkus?.[0]?.packPriceStr }}</span>
                  </div>
                  <div class="four-right">
                    <span class="quantity-badge">x{{ item.quantity }}</span>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>


    <div class="wrapper-box">
      <div class="wrapper-box-content">
        <div class="other-info">
          <!-- 配送费 -->
          <div class="info-item">
            <div class="info-label">配送费</div>
            <div class="info-value">￥{{ deliveryFeeStr ? Number(deliveryFeeStr)?.toFixed(2) : 0 }}</div>
          </div>

          <!-- 服务费 -->
          <!-- <div class="info-item">
            <div class="info-label">服务费</div>
            <div class="info-value">￥{{ serviceChargeStr ? Number(serviceChargeStr)?.toFixed(2) : 0 }}</div>
          </div> -->

          <!-- 打包费 -->
          <div class="info-item">
            <div class="info-label">打包费 <span style="font-size: 24rpx; color: #999999;">（合计）</span> </div>
            <div class="info-value">￥{{ packChargeStr ? Number(packChargeStr)?.toFixed(2) : 0 }}</div>
          </div>

          <!-- 备注信息 -->
          <div class="info-item remark-item">
            <div class="info-label">备注</div>
            <div class="info-input">
              <textarea v-model="remark" placeholder="请填写备注信息（选填）" class="remark-textarea" maxlength="100"
                auto-height />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加购物车弹出层 -->
    <wd-overlay :show="showCart" @click="showCart = false" zIndex="10">
      <view class="Shopping-cart-wrapper" @click.stop>
        <div class="wrapper-box">
          <div class="wrapper-box-header">
            <div class="wrapper-box-header-left">
              已选商品
            </div>
            <div class="wrapper-box-header-right" @click="clearCart">
              清空
            </div>
          </div>
          <div class="wrapper-box-content">
            <div class="item-content">
              <template v-for="(item, index) in cartItems" :key="index">
                <div class="item-content-item">
                  <img :src="item.thumbnail" alt="">
                  <div class="item-content-item-title">
                    <div class="one">{{ item.goodsName }}</div>
                    <div class="two">
                      <template v-for="(spec, specIndex) in item.specDetails" :key="specIndex">
                        <span>{{ spec.optionName }}: {{ spec.specsName }}
                          <span v-if="Number(spec.specsPrice) > 0" style="color: red;"> +￥{{ spec.specsPrice }}</span>
                          <span v-if="specIndex < item.specDetails.length - 1">; </span>
                        </span>
                      </template>
                    </div>
                    <div class="four">
                      <div class="four-left">
                        <span>￥</span>
                        <span>{{
                          (
                            parseFloat(item.listGoodsSkus?.[0]?.priceStr || item.listGoodsSkus?.[0]?.marketPrice || 0) +
                            (item.specDetails?.reduce((sum, spec) => sum + (parseFloat(spec.specsPrice) || 0), 0) || 0)
                          ).toFixed(2)
                        }}</span>
                        <!-- <span v-if="item.listGoodsSkus?.[0]?.packPriceStr"
                          style="font-size: 20rpx; margin-left: 8rpx;">+打包费¥{{
                            item.listGoodsSkus?.[0]?.packPriceStr
                          }}</span> -->
                      </div>
                      <div class="four-right">
                        <img class="img-left" src="../static/imgs/jianhao.png" alt="" @click="decreaseQuantity(index)">
                        <div>{{ item.quantity }}</div>
                        <img class="img-right" src="../static/imgs/Merchant/tianjia2.png" alt=""
                          @click="increaseQuantity(index)">
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </view>
    </wd-overlay>

    <!-- 底部支付按钮 -->
    <div class="Shopping-cart">
      <div class="Shopping-cart-box">
        <div class="Shopping-cart-box-img" @click="toggleCart">
          <img src="../static/imgs/goumai.png" alt="">
          <div class="Shopping-cart-box-img-text">{{ totalQuantity }}</div>
        </div>
        <div class="Shopping-cart-box-text">
          <div class="Shopping-cart-box-text-top">合计 ￥ <span>{{ Number(totalAmountStr) }}</span></div>
        </div>
        <div class="Shopping-cart-box-botton active" @click.stop="submitOrder">
          立即支付
        </div>
      </div>
    </div>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useLoginStore } from '@/stores/login.js'
const loginStore = useLoginStore()
// 声明响应式购物车数据
const cartItems = ref([])
const totalAmountStr = ref(0)
const remark = ref('') // 备注信息
const deliveryFeeStr = ref(0) // 默认配送费
const serviceChargeStr = ref(0) // 服务费
const packChargeStr = ref(0) // 打包费
const originalPackCharge = ref(0) // 原始店铺打包费
const extendId = ref('')
// 添加购物车弹出框的状态变量
const showCart = ref(false)

// 在页面加载时获取购物车数据
onLoad((options) => {
  console.log(options, 'options');
  if (options.extendId) {
    extendId.value = options.extendId
  }
  if (options.cartData) {
    // 解析购物车数据
    const cartData = JSON.parse(decodeURIComponent(options.cartData))
    cartItems.value = cartData
    console.log(cartItems.value, 'cartItems.value购物车数据==============');
    // 如果传递了配送费，则使用传递的配送费
    if (options.deliveryFeeStr != '') {
      const fee = parseFloat(options.deliveryFeeStr)
      deliveryFeeStr.value = !isNaN(fee) ? fee : 0
      console.log(deliveryFeeStr.value, 'deliveryFeeStr.value')
    }

    // 如果传递了服务费，则使用传递的服务费
    if (options.serviceChargeStr) {
      const fee = parseFloat(options.serviceChargeStr)
      serviceChargeStr.value = !isNaN(fee) ? fee : 0
    }

    // 如果传递了打包费，则使用传递的打包费
    if (options.packChargeStr) {
      const fee = parseFloat(options.packChargeStr)
      originalPackCharge.value = !isNaN(fee) ? fee : 0
      packChargeStr.value = originalPackCharge.value
    }

    // 计算总金额
    calculateTotal()
  }
  loadAddressList()
  uni.$on('selectAddress', handleAddressSelected);
})

onUnload(() => {
  uni.$off('selectAddress', handleAddressSelected);
})

const Address = ref({
  contactAddress: '请选择地址'
})
const handleAddressSelected = (address) => {
  Address.value = address
  console.log('已选择地址:', address)
}
// 计算购物车总金额
const calculateTotal = () => {
  // 商品总价（商品价格 + 规格额外价格）
  const goodsTotal = cartItems.value.reduce((sum, item) => {
    // ⚠️ 重要：转换成数字
    const priceStr = parseFloat(item.listGoodsSkus?.[0]?.priceStr || item.listGoodsSkus?.[0]?.marketPrice || 0)

    // 计算该商品的规格额外价格
    const specAdditionalPrice = item.specDetails?.reduce((specSum, spec) => {
      return specSum + (parseFloat(spec.specsPrice) || 0)
    }, 0) || 0

    // 商品总价 = (基础价格 + 规格价格) * 数量
    return sum + ((priceStr + specAdditionalPrice) * item.quantity)
  }, 0)

  // 计算所有商品的打包费总和
  const itemsPackFee = cartItems.value.reduce((sum, item) => {
    // ⚠️ 这里也要转换成数字
    const packPriceStr = parseFloat(item.listGoodsSkus?.[0]?.packPriceStr || 0)
    return sum + (packPriceStr * item.quantity)
  }, 0)

  // 更新打包费（原始店铺打包费 + 商品打包费）
  packChargeStr.value = originalPackCharge.value + itemsPackFee

  // 总金额 = 商品总价 + 配送费 + 服务费 + 打包费
  totalAmountStr.value = goodsTotal + deliveryFeeStr.value + serviceChargeStr.value + packChargeStr.value
}

// 计算属性：格式化后的总金额
const formattedTotal = computed(() => {
  return Number(totalAmountStr.value).toFixed(2)
})

// 计算属性
const totalQuantity = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

// 提交订单方法
const submitOrder = async () => {
  console.log('??????????????');

  // 检查是否已选择地址
  if (!Address.value.contactAddress || Address.value.contactAddress === '请选择地址') {
    uni.showToast({
      title: '请先选择收货地址',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({ title: '提交中...' })
    const dataList = []
    cartItems.value.forEach(item => {
      if (item.specDetails) {
        item.specDetails.forEach(spec => {
          delete spec.specsPrice
        })
      }
      // 计算该商品的规格额外价格
      const specAdditionalPrice = item.specDetails?.reduce((sum, spec) => {
        return sum + (parseFloat(spec.specsPrice) || 0)
      }, 0) || 0

      // 基础价格
      const basePrice = parseFloat(item.listGoodsSkus?.[0]?.priceStr || item.listGoodsSkus?.[0]?.marketPrice || 0)

      // 总价格 = 基础价格 + 规格额外价格
      const totalPrice = basePrice + specAdditionalPrice

      dataList.push({
        categoryId: item.categoryId, // 商品类目id
        goodsId: item.goodsId, // 商品id
        goodsName: item.goodsName, // 商品名称
        priceStr: totalPrice.toFixed(2), // 商品价格（包含规格价格）
        goodsNum: item.quantity, // 商品数量
        thumbnail: item.thumbnail, // 商品缩略图
        skuDesc: item.specifications.join('，'), // 商品规格描述
        goodsSpecsList: item.specDetails || [], // 规格详情（可选，看后端是否需要）
        skuId: item.listGoodsSkus?.[0]?.skuId, // 商品sku id
        remark: remark.value, // 备注
        addressId: Address.value.addressId, // 地址id
      })
    });

    // 订单创建
    const res = await Fetch('shopping/order/placeAnOrder', {
      method: 'post',
      data: dataList,
    })

    console.log(res, 'result');


    if (res.data.code === 200) {
      const orderId = res.data.data.orderId
      const openid = loginStore.openId
      // 支付订单创建
      const PaymentObj = await Fetch('shopping/pays/wechatJsapi', {
        method: 'get',
        data: {
          orderId,
          openid,
        }
      })
      const payData = PaymentObj.data.value
      console.log(payData, 'payData____________');
      // 3. 调起微信支付
      wx.requestPayment({
        timeStamp: payData.timeStamp,
        nonceStr: payData.nonceStr,
        package: payData.package,
        signType: payData.signType,
        paySign: payData.paySign,
        success() {
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          })

          // 清空购物车数据
          uni.removeStorageSync('cartData')

          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/OrderDetails?id=' + res.data.data.orderId
            })
            if (extendId.value) {
              Fetch(`shopping/extend/${extendId.value}`, {
                method: 'DELETE',
              })
            }
          }, 1500)
        },
        fail(err) {
          // uni.reLaunch({
          //   url: `/pages/PaymentFail?amount=${totalAmountStr.value}&orderNo=${res.data.data.orderNo}&reason=支付失败`
          // })
          uni.reLaunch({
            url: `/pages/OrderDetails?id=${res.data.data.orderNo}&from=payment&openid=${loginStore.openId}&orderId=${res.data.data.orderNo}`
          })
          if (extendId.value) {
            Fetch(`shopping/extend/${extendId.value}`, {
              method: 'DELETE',
            })
          }
          console.error('支付失败：', err);
        }
      });

    } else {
      // uni.showToast({
      //   title: '支付失败：' + res.data.msg,
      //   icon: 'none'
      // })
      uni.showModal({
        title: '支付失败：',
        content: res.data.msg,
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
          }
        }
      })
    }
  } catch (error) {
    console.error('支付错误:', error)
    // uni.showToast({
    //   title: '支付过程中发生错误',
    //   icon: 'none'
    // })
    uni.showModal({
      title: '支付失败：',
      content: '支付过程中发生错误',
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
        }
      }
    })
  } finally {
    uni.hideLoading()
  }
}

// 跳转到地址页面
const goToAddressPage = () => {
  uni.navigateTo({
    url: '/pages-shift/Address?isReturn=true',
    fail: (error) => {
      console.error('跳转失败:', error)
      uni.showToast({
        title: '跳转失败',
        icon: 'none'
      })
    }
  })
}

// 切换购物车弹出层显示状态
const toggleCart = () => {
  showCart.value = !showCart.value
}

// 清空购物车
const clearCart = () => {
  uni.showModal({
    title: '提示',
    content: '确认清空购物车吗？',
    success: (res) => {
      if (res.confirm) {
        cartItems.value = []
        calculateTotal()
        showCart.value = false
      }
    }
  })
}

// 增加商品数量
const increaseQuantity = (index) => {
  if (cartItems.value[index]) {
    cartItems.value[index].quantity += 1
    calculateTotal()
  }
}

// 减少商品数量
const decreaseQuantity = (index) => {
  if (cartItems.value[index] && cartItems.value[index].quantity > 1) {
    cartItems.value[index].quantity -= 1
    calculateTotal()
  } else if (cartItems.value[index] && cartItems.value[index].quantity === 1) {
    cartItems.value.splice(index, 1)
    calculateTotal()

    if (cartItems.value.length === 0) {
      showCart.value = false
      // 添加判断，购物车为空时返回上一页
      uni.showModal({
        title: '提示',
        content: '购物车已清空，将返回商品页面',
        showCancel: false,
        success: () => {
          uni.navigateBack({
            delta: 1
          })
        }
      })
    }
  }
}

// 获取用户地址数据拿默认地址
const loadAddressList = async () => {
  try {
    const { status, data } = await Fetch(`shopping/address/list`, { method: 'get' })
    console.log(status, data);

    if (status === 200 && data.code === 200) {
      data.rows.forEach(item => {
        if (item.defaultAddress == 1) {
          Address.value = item
        }
      })
    }
  } catch (error) {
    console.error('加载地址列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'error'
    })
  } finally {
  }
}
</script>

<style lang="scss" scoped>
.payment-container {
  height: 100vh;
  background: #F5F5F5;
  padding: 10px 20rpx;

  .nav-bar {
    padding-left: 20rpx;

    .nav-title {
      display: flex;
      align-items: center;

      image {
        width: 36rpx;
        height: 36rpx;
      }

      .address-icon {
        margin-right: 16rpx;
      }

      .title {
        flex: 1;
        margin-right: auto;
      }
    }

    .nav-info {
      display: flex;
      font-size: 24rpx;
      font-weight: 400;
      color: #666666;
      line-height: 34rpx;
      text-align: left;
      font-style: normal;
      text-transform: none;
      margin-top: 10rpx;

      view {
        &:nth-child(1) {
          margin-right: 16rpx;
        }
      }
    }
  }



  .wrapper-box {

    width: 710rpx;
    background: #FFFFFF;
    border-radius: 30rpx;
    padding: 30rpx;
    box-sizing: border-box;
    margin: 24rpx auto 0;

    .wrapper-box-content {
      .item-content {
        .item-content-item {
          display: flex;
          margin-bottom: 30rpx;

          image {
            width: 128rpx;
            height: 132rpx;
            border-radius: 16rpx 16rpx 16rpx 16rpx;
            margin-right: 20rpx;
          }

          .item-content-item-title {
            flex: 1;
            width: 100%;

            .one {
              height: 40rpx;
              font-weight: bold;
              font-size: 28rpx;
              color: #000000;
              line-height: 40rpx;
              text-transform: none;
            }

            .two {
              height: 34rpx;
              font-weight: 400;
              font-size: 24rpx;
              color: #999999;
              line-height: 34rpx;
              text-transform: none;
            }


            .four {
              display: flex;
              align-items: flex-end;
              width: 100%;

              image {
                width: 46rpx;
                height: 46rpx;
              }

              .four-left {
                margin-right: auto;
                margin-top: 30rpx;
                height: 44rpx;
                font-weight: bold;
                font-size: 32rpx;
                color: #EA5838;
                line-height: 44rpx;
                text-transform: none;

                label {
                  &:nth-child(1) {
                    height: 34rpx;
                    font-weight: bold;
                    font-size: 24rpx;
                    color: #EA5838;
                    line-height: 34rpx;
                    text-transform: none;
                  }
                }
              }
            }
          }
        }
      }
    }
  }



  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 0 24rpx 0;
    border-bottom: 1px solid #f5f5f5;
  }

  .remark-item {
    align-items: flex-start;
    padding: 24rpx 0;
  }

  .remark-textarea {
    width: 100%;
    min-height: 40rpx;
    /* 初始高度较低 */
    max-height: 200rpx;
    /* 限制最大高度 */
    text-align: right;
    font-size: 28rpx;
    color: #666;
    padding: 10rpx 0;
    line-height: 1.4;
  }

  .info-label {
    font-size: 28rpx;
    color: #333;
  }

  .info-value {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }

  .info-input {
    width: 70%;
  }

  .Shopping-cart {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 166rpx;
    background: #FFFFFF;
    z-index: 100;
    padding: 22rpx 30rpx 64rpx 30rpx;
    box-sizing: border-box;

    .Shopping-cart-box {
      display: flex;
      align-items: center;

      .Shopping-cart-box-img {
        position: relative;

        .Shopping-cart-box-img-text {
          position: absolute;
          top: -10rpx;
          right: -10rpx;
          padding: 2rpx 14rpx;
          color: white;
          border-radius: 50%;
          background: #EB4E27;
        }
      }

      .Shopping-cart-box-text {
        .Shopping-cart-box-text-top {
          height: 36rpx;
          font-weight: bold;
          font-size: 26rpx;
          color: #EB4E36;
          margin-left: 32rpx;
          line-height: 36rpx;

          label {
            font-size: 40rpx;
          }

          margin-bottom: 10rpx;
        }

        .Shopping-cart-box-text-bottom {
          height: 28rpx;
          font-size: 20rpx;
          color: #676869;
          line-height: 28rpx;
          margin-left: 32rpx;
        }
      }

      .Shopping-cart-box-botton {
        width: 200rpx;
        height: 90rpx;
        background: #BCBCBD;
        border-radius: 46rpx 46rpx 46rpx 46rpx;
        font-weight: bold;
        font-size: 36rpx;
        line-height: 90rpx;
        color: #FFFFFF;
        text-align: center;
        margin-left: auto;

        &.active {
          background: #F9DC40;
        }
      }
    }

    image {
      width: 74rpx;
      height: 80rpx;
    }
  }

  .four-right {
    display: flex;
    align-items: center;

    .quantity-badge {
      font-size: 24rpx;
      color: #666;
      padding: 4rpx 10rpx;
      border-radius: 20rpx;
      background: #f5f5f5;
    }
  }
}

// 添加购物车弹出框样式
.Shopping-cart-wrapper {
  width: 750rpx;
  background: #F1F1F1;
  border-radius: 36rpx 36rpx 0rpx 0rpx;
  padding: 20rpx;
  box-sizing: border-box;
  position: fixed;
  bottom: 166rpx;

  .wrapper-box {
    width: 710rpx;
    background: #FFFFFF;
    border-radius: 30rpx;
    padding: 30rpx;
    box-sizing: border-box;
    margin: 0 auto;

    .wrapper-box-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 40rpx;

      .wrapper-box-header-left {
        height: 44rpx;
        font-weight: bold;
        font-size: 32rpx;
        color: #222425;
        line-height: 44rpx;
      }

      .wrapper-box-header-right {
        height: 34rpx;
        font-weight: 400;
        font-size: 24rpx;
        color: #999999;
        line-height: 34rpx;
      }
    }

    .wrapper-box-content {
      .item-content {
        .item-content-item {
          display: flex;
          margin-bottom: 40rpx;

          image {
            width: 128rpx;
            height: 132rpx;
            border-radius: 16rpx 16rpx 16rpx 16rpx;
            margin-right: 20rpx;
          }

          .item-content-item-title {
            flex: 1;
            width: 100%;

            .one {
              height: 40rpx;
              font-weight: bold;
              font-size: 28rpx;
              color: #000000;
              line-height: 40rpx;
              text-transform: none;
            }

            .two {
              height: 34rpx;
              font-weight: 400;
              font-size: 24rpx;
              color: #999999;
              line-height: 34rpx;
              text-transform: none;
            }


            .four {
              display: flex;
              align-items: flex-end;
              width: 100%;

              image {
                width: 46rpx;
                height: 46rpx;
              }

              .four-left {
                margin-right: auto;
                margin-top: 30rpx;
                height: 44rpx;
                font-weight: bold;
                font-size: 32rpx;
                color: #EA5838;
                line-height: 44rpx;
                text-transform: none;

                label {
                  &:nth-child(1) {
                    height: 34rpx;
                    font-weight: bold;
                    font-size: 24rpx;
                    color: #EA5838;
                    line-height: 34rpx;
                    text-transform: none;
                  }
                }
              }
            }

            .four-right {
              display: flex;
              align-items: center;

              .img-left,
              .img-right {
                width: 46rpx;
                height: 46rpx;
                margin: 0rpx;
              }

              .img-left {
                margin-right: 20rpx;
              }

              .img-right {
                margin-left: 20rpx;
              }
            }
          }
        }
      }
    }
  }


}
</style>
